package com.sunday.fangbeibei.activity;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.sunday.fangbeibei.R;
import com.sunday.fangbeibei.adapter.RecordCustomAdapter;
import com.sunday.fangbeibei.cache.ApplicationCache;
import com.sunday.fangbeibei.constants.ApplicationConstants;
import com.sunday.fangbeibei.http.HttpResponseInterface;
import com.sunday.fangbeibei.http.HttpTool;
import com.sunday.fangbeibei.orm.BaseResult;
import com.sunday.fangbeibei.orm.CustomInfo;
import com.sunday.fangbeibei.orm.CustomResult;
import com.sunday.fangbeibei.orm.HouseInfo;
import com.sunday.fangbeibei.widget.ActionSheet;
import com.sunday.fangbeibei.widget.ActionSheet.ActionSheetListener;
/**
 * 
 * @author 晨曦
 *
 */
public class RecordCustomActivity extends BaseFragmentActivity implements OnClickListener,OnItemClickListener,HttpResponseInterface,ActionSheetListener{

	private ListView listview;
	private TextView number;
	private EditText searchet;
	private ImageView searchiv;
	
	private List<CustomInfo> list;
	
	private Map<String, CustomInfo> selectCustom;
	
	private HouseInfo info;
	
	private RecordCustomAdapter adapter;
	
	@Override
	protected void createActivity(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setContentView(R.layout.record_custom_layout);
		info=(HouseInfo) getIntent().getSerializableExtra("info");
		selectCustom=new HashMap<String, CustomInfo>();
		loadView();
		loadData();
	}

	private void loadView(){
		

		TextView title=(TextView) findViewById(R.id.title);
		title.setText("报备客户");
		ImageView back=(ImageView) findViewById(R.id.back);
		back.setOnClickListener(this);
		
		listview=(ListView) findViewById(R.id.listview);
		TextView name=(TextView) findViewById(R.id.name);
		TextView add=(TextView) findViewById(R.id.add);
		TextView commit=(TextView) findViewById(R.id.commit);
		number=(TextView) findViewById(R.id.number);
		
		listview.setOnItemClickListener(this);
		
		name.setText(info.getName());		
		searchet=(EditText) findViewById(R.id.searchet);
		searchiv=(ImageView) findViewById(R.id.searchiv);
		
		searchiv.setOnClickListener(this);
		
		add.setOnClickListener(this);
		commit.setOnClickListener(this);
		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.back:
			finish();
			break;
		case R.id.searchiv:
			loadData();
			break;
		case R.id.commit:
			if(selectCustom.size()==0){
				Toast.makeText(mContext, "请选择用户", Toast.LENGTH_SHORT).show();
				return;
			}
			show("");
			RequestParams params=new RequestParams();
			params.add("userId", ApplicationCache.INSTANCE.getUserInfo().getId());
			params.add("premisesId", info.getId());
			
			String ids="";
			Iterator it=selectCustom.entrySet().iterator();
			while(it.hasNext()){
				Map.Entry entry=(Entry) it.next();
				if(ids.equals("")){
					ids=(String) entry.getKey();
				}else{
					ids=ids+","+entry.getKey();
				}
			}
/*			for(CustomInfo in:list){
				if(in.isSelected()){
					if(ids.equals("")){
						ids=in.getId();
					}else{
						ids=ids+","+in.getId();
					}
				}
			}*/
			
			params.add("customerId", ids);
			HttpTool.HttpPost(1, this, ApplicationConstants.SERVER_URL+"/mobi/report/batchsavereport", params, this, new TypeToken<BaseResult>() {
			}.getType());
			break;
		case R.id.add:
			setTheme(R.style.ActionSheetStyleIOS7);
			ActionSheet.createBuilder(mContext, getSupportFragmentManager())
			.setCancelButtonTitle("取消")
			.setOtherButtonTitles("从通讯录添加", "直接添加")
			.setCancelableOnTouchOutside(true).setListener(this).show();
			break;
		}
	}
	
	
	private void loadData(){
		
		RequestParams params=new RequestParams();
		params.add("userId", ApplicationCache.INSTANCE.getUserInfo().getId());
		params.add("premisesId", info.getId());
		params.add("key", searchet.getText().toString());
		HttpTool.HttpPost(0, this, ApplicationConstants.SERVER_URL+"/mobi/customer/getcustomerbyPreid", params, this, new TypeToken<CustomResult>() {
		}.getType());
		
	}
	
	
	@Override
	public void onResponse(int requsetCode, boolean resultStatus, Object result) {
		// TODO Auto-generated method stub
		disMiss();
		switch(requsetCode){
		case 0:
			if(resultStatus){
				CustomResult re=(CustomResult) result;
				list = re.getList();
				if(list!=null){
					
					for(CustomInfo info:list){
						if(selectCustom.get(info.getId())!=null){
							info.setSelected(true);
							selectCustom.put(info.getId(), info);
						}
					}
				}
				
				adapter=new RecordCustomAdapter(mContext, list);
				listview.setAdapter(adapter);
			}
			break;
		case 1:
			if(resultStatus){
				Toast.makeText(mContext, "报备成功!", Toast.LENGTH_SHORT).show();
				finish();
			}else{
				BaseResult res=(BaseResult) result;
				switch(res.getCode()){
				case -1:
					Toast.makeText(mContext, "系统异常！", Toast.LENGTH_SHORT).show();
					break;
				case -4:
					Toast.makeText(mContext, "包含错误的用户id！", Toast.LENGTH_SHORT).show();
					break;
				case -5:
					Toast.makeText(mContext, "包含没有权限的用户id！", Toast.LENGTH_SHORT).show();
					break;
				default:
					Toast.makeText(mContext, "报备失败!", Toast.LENGTH_SHORT).show();
					break;
				}
			}
			break;
		}
	}

	@Override
	public void onFailure() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		CustomInfo info=(CustomInfo) view.getTag();
		info.setSelected(!info.isSelected());
		
		if(info.isSelected()){
			selectCustom.put(info.getId(), info);
		}else{
			selectCustom.remove(info.getId());
		}
		
		number.setText(selectCustom.size()+"");
		
		adapter.notifyDataSetChanged();
	}

	

	@Override
	public void onOtherButtonClick(ActionSheet actionSheet, int index) {
		// TODO Auto-generated method stub
		if(index==0){
			 Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
             startActivityForResult(intent, 123);
		}else{
			Intent in=new Intent(mContext, CustomAddActivity.class);
			in.putExtra("id", info.getId());
			startActivity(in);
			finish();
		}
	}


	@Override
	public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode==FragmentActivity.RESULT_OK){
			if(requestCode==123){
				
				 String username,usernumber="";
				
				 ContentResolver reContentResolverol = mContext.getContentResolver();
	             Uri contactData = data.getData();
	             Cursor cursor = managedQuery(contactData, null, null, null, null);
	             cursor.moveToFirst();
	             username = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
	             String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
	             Cursor phone = reContentResolverol.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
	             while (phone.moveToNext()) {
	                 usernumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
	             }
				Intent in=new Intent(mContext, CustomAddActivity.class);
				in.putExtra("name", username);
				in.putExtra("phone", usernumber);
				in.putExtra("id", info.getId());
				startActivity(in);
				finish();
			}
		}
	}

	
}
